// 是否改变了站点

var changeSite = false;

var timeCount = 5;

var base_uri = 'https://www.haimaihome.com';
// var base_uri = 'http://www.haimaihome.local';

var backgroudData;

var selectSite = 'com';

var currentProfile;

var isAmazonLogined = chrome.extension.getBackgroundPage().isAmazonLogin;

var faieldLog;

var autoRefreshWindow;


var sites = ['com', 'co.jp', 'ca', 'co.uk', 'de', 'fr', 'it', 'es', 'com.mx', 'in'];
var backgroudData;
var customerProfile;
var currentProfile;

$(function ($) {

    backgroudData = chrome.extension.getBackgroundPage().articleData;
    customerProfile = chrome.extension.getBackgroundPage().customerProfile;
    currentProfile = chrome.extension.getBackgroundPage().currentSeller;
    isLogin(function () {
        $('#loginBox').hide();
        $('#contentBox').show();


        autoRefreshWindow = setInterval(function () {
            console.log('刷新window');
            if (isAmazonLogined == 1) {
                window.location.reload();
            } else {
                clearInterval(autoRefreshWindow);
            }
        }, 4000);
        if (currentProfile === undefined && customerProfile.sellerId) {
            console.log('无信息');
            //若登录用户没有信息，则通过当前profile去获取market内容
            $.ajax({
                url: base_uri + '/api/getMarketplaces/' + customerProfile.sellerId,
                dataType: 'json',
                method: 'GET',
                success: function (data) {
                    if (data.code == 0) {
                        var profile = data.data;
                        chrome.runtime.sendMessage({
                            type: 'currentSellerCatch',
                            data: profile
                        });
                        setTips();
                    } else {
                        showTips(data.message);
                    }
                },
                error: function (data) {
                }
            });
            return;
        }

        if (customerProfile.sellerId == '') {
            if (isAmazonLogined == 1) {
                showTips('<span><i class="fa fa-refresh fa-spin"></i> 正在登录亚马逊后台端，若长时间无反应请刷新</span>');
            } else {
                showTips('未登录亚马逊' + '<button class="btn btn-info openNewWindow" data-function="openSite">去登录</button>');
            }
        } else {
            if (customerProfile.sellerId !== currentProfile.SellerId) {
                showTips('登陆的亚马逊账户与平台绑定的账户不匹配' + '<button class="btn btn-info openNewWindow" data-function="openSite">重新登录</button>');
                return;
            }
            setTips();
        }
    });

    $('#contentBox').on('click', '.openNewWindow',function () {
        var func = $(this).data('function');
        if (func === 'openSite') {
            openSite();
        }
    });


    $('#loginBox').validator().on('submit', function (e) {
        if (e.isDefaultPrevented()) {

        } else {
            layer.load(2);
            setTimeout(function(){
                layer.closeAll('loading');
            }, 10000);
            e.preventDefault();
            $.ajax({
                url: base_uri + '/api/login',
                data: $('#loginBox').serialize(),
                dataType:'json',
                method: 'POST',
                success: function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0) {
                        layer.msg('登录成功');
                        if (customerProfile === undefined || customerProfile.sellerId == '') {
                            showTips('未登录亚马逊' + '<button class="btn btn-info openNewWindow" data-function="openSite">去登录</button>');
                        } else {
                            if (customerProfile.sellerId !== currentProfile.SellerId) {
                                showTips('登陆的亚马逊账户与平台绑定的账户不匹配' + '<button class="btn btn-info openNewWindow" data-function="openSite">重新登录</button>');
                                return;
                            }
                            setTips();
                        }
                        $('#loginBox').hide();
                        $('#contentBox').show();
                    } else {
                        layer.msg(data.message);
                    }
                },
                error: function (data) {
                    layer.msg('请求错误，请刷新游览器重试');
                }
            });
        }
    });
});


$('#refreshAccount').on('click', function () {
    $('#logPanel').hide();
    $('#loading').show();
    $('#refreshAccount').attr('disabled', 'disabled');
    if (customerProfile !== undefined && customerProfile.sellerId != '') {
        $.ajax({
            url: base_uri + '/api/getMarketplaces/' + customerProfile.sellerId,
            dataType: 'json',
            method: 'GET',
            success: function (data) {
                if (data.code == 0) {
                    var profile = data.data;
                    chrome.runtime.sendMessage({
                        type: 'currentSellerCatch',
                        data: profile
                    });
                    setTips();
                } else {
                    showTips(data.message);
                    $('#loading').hide();
                }
            },
            error: function (data) {
            }
        });
    }
});


function setTips() {
    $('#loading').show();
    var tipInterval = setInterval(function () {
        var backGround = chrome.extension.getBackgroundPage().articleData;
        console.log('进入tips循环');
        console.log(backGround);
        var isSearching = backGround.isSearching;
        var tips = backGround.info;
        if ( ! isSearching) {
            $('#loading').hide();
            $('#refreshAccount').removeAttr("disabled").show();
        }
        if (tips !== undefined && tips != '') {
            showTips(tips);
        }
        showPanel(true);
        if (!isSearching) {
            clearInterval(tipInterval);
        }
    }, 2000);
}

function showPanel(shoLog) {
    if (shoLog) {
        $('#logPanel').append(getLogPanelHtml()).show();
    } else {
        $('#logPanel').hide();
    }

}

function openSite() {
    window.open("https://sellercentral.amazon." + selectSite  + "/home");
}

function showTips(tips) {
    $('#tips').html(tips).show();
}

function getLogPanelHtml()
{
    var showLog = '<ul>';
    var currentProfile = chrome.extension.getBackgroundPage().currentSeller;
    var marketplaces = currentProfile.marketplace;
    for (var i = 0; i < marketplaces.length; i++) {
        var site = marketplaces[i].site;
        var logs = marketplaces[i].traffics;
        for (var j=0; j < logs.length; j++) {
            showLog += getLogLi(site, logs[j], 'success');
        }
    }
    showLog += '</ul>';
    return showLog;
}


// 判断是否登录
function isLogin(callback) {


    $.ajax({

        type: "get",

        url: base_uri + '/api/checkLogin',

        timeout: 5000,

        dataType: 'json',

    }).done(function (response) {

        var code = response.code;
        var data = response.data;
        if (code == 0) {
            callback();
        } else if (code == -1){
            $('#contentBox').hide();
            $('#loginBox').show();
        }
    }).fail(function (result, textStatus) {
    });
}

function getLogLi(site, date, status)
{
    if (status == 'success') {
        return '<li>站点['+site+']:'+date+'  <span style="color: green">同步成功!</span></li>';
    }  else {
        return '<li>站点['+site+']:'+date+' <span style="color: red">失败!</span></li>';
    }
}